# coding=utf-8

'''create by pbc for docker api'''
import json

import docker


def getNodeInfo():
    '''获取节点信息功能'''
    CLIENT = docker.from_env()
    nodeInfo = CLIENT.info()
    return nodeInfo


def getNodeImages():
    '''获取所有镜像列表'''
    CLIENT = docker.APIClient()
    imageList = CLIENT.images()
    return imageList


def getNodeAllContainer():
    '''获取节点所有容器列表'''
    CLIENT = docker.APIClient()
    containerList = CLIENT.containers(all=True)
    return containerList


def createContainer(arg_dict):
    CLIENT = docker.from_env()
    '''创建一个容器'''
    print('创建一个容器:')
    print(arg_dict)
    # docker run -p 2022:22 --restart=always --name con_ubuntu1604_dabao -it -v /root/pbc/ubuntu1604_dir:/root/ubuntu1604_dir 0112cef7b5aa /bin/bashi
    # CLIENT.containers.run(image='pangbaochuan', command='/bin/bash', name='portstest', auto_remove=False,
    #                       cap_add=["SYS_ADMIN", "MKNOD"], mem_limit='512m', cpu_quota=200000, detach=True,
    #                       stdin_open=True, tty=False, volumes={'/tmp': {'bind': '/home/user', 'mode': 'rw'},
    #                                                            '/root/soft': {'bind': '/root/soft', 'mode': 'rw'}},
    #                       ports={22: 8022, 8008: 8058})

    # {'container_arg_mem': '222', 'action': 'add', 'container_arg_name': 't2', 'container_arg_core': '1',
    #  'container_arg_ports': '', 'container_arg_dirs': '', 'container_arg_command': '/bin/bash',
    #  'container_arg_image': 'testhttp:v4', 'hostaddress': '35.com', 'container_arg_nodes': 'node35.com'}

    image = arg_dict['container_arg_image']
    command = arg_dict['container_arg_command']
    name = arg_dict['container_arg_name']
    mem_limit = arg_dict['container_arg_mem'] + 'm'
    cpu_quota = int(arg_dict['container_arg_core']) * 100000

    if str(arg_dict['container_arg_ports']) == "":
        ports = {}
    else:
        ports = {}
        port_list = str(arg_dict['container_arg_ports']).split(',')
        for i in range(len(port_list)):
            tmp_item = port_list[i]
            ports[int(tmp_item.split(':')[0])] = int(tmp_item.split(':')[1])

    if str(arg_dict['container_arg_dirs']) == "":
        volumes = {}
    else:
        volumes = {}
        volumes_list = str(arg_dict['container_arg_dirs']).split(',')
        for i in range(len(volumes_list)):
            tmp_item = volumes_list[i]
            volumes[tmp_item.split(':')[0]] = {'bind': tmp_item.split(':')[1], 'mode': 'rw'}

    print(image, command, name, mem_limit, cpu_quota, ports, volumes)

    ret = CLIENT.containers.run(
        image=image,
        command=command,
        name=name,
        mem_limit=mem_limit,
        cpu_quota=cpu_quota,
        ports=ports,
        volumes=volumes,
        detach=True,
        stdin_open=True,
        tty=False,
        auto_remove=False,
        cap_add=["SYS_ADMIN", "MKNOD"]
    )
    print('create container retuvalue',ret)
    return None


def startContainer(arg_dict):
    '''启动一个容器'''
    CLIENT = docker.APIClient()
    ret = CLIENT.start(arg_dict.get('id'))
    return ret


def stopContainer(arg_dict):
    '''停止一个容器'''
    CLIENT = docker.APIClient()
    ret = CLIENT.stop(arg_dict.get('id'))
    return ret


def deleteContainer(arg_dict):
    '''删除一个容器'''
    CLIENT = docker.APIClient()
    ret = CLIENT.remove_container(arg_dict.get('id'))
    return ret


def exportContainerToImage(arg_dict):
    import os
    cmd_str = 'docker export -o ' + arg_dict.get('name') + ' ' + arg_dict.get('id')
    ret = os.system(cmd_str)
    return ret


def dockerPullImageToDocker(arg_dist):
    image_name = arg_dist.get("image_name")
    image_list = getNodeImages()
    image_name = "['" + image_name + "']"
    print(image_name)
    for item in range(len(image_list)):
        item_name = image_list[item].get("RepoTags")
        print(item_name,image_name)
        if image_name == item_name:
            print("代表该镜像已经存在")
            return -2#代表该镜像已经存在

    return 0


def importImageToDocker(arg_dict):
    import os
    cmd_str = 'docker import http://' + arg_dict.get('url') + ':8055/download-' + arg_dict.get(
        'image_tar_name') + ' ' + arg_dict.get('image_name')
    print(cmd_str)

    download_str = 'wget https://' + arg_dict.get('url') + ':8055/download-' + arg_dict.get('image_tar_name') + ' -P /tmp/'  + ' --no-check-certificate'
    print("download_str:",download_str)
    os.system(download_str)

    import_str = 'docker import ' + '/tmp/download-' + arg_dict.get('image_tar_name') + ' ' + arg_dict.get('image_name')
    print('import_str:',import_str)
    ret = os.system(import_str)

    #ret = os.system(cmd_str)
    print(ret)
    return ret


def deleteImages(arg_dict):
    id = arg_dict.get('id')
    print(id)
    import docker
    client = docker.from_env()
    ret = client.images.remove(id)
    return ret


def createLocalImageFunc(arg_dict):
    import os
    image_name = arg_dict['image_name']
    container_name = arg_dict['container_name']
    cmd_str = 'docker commit ' + container_name + ' ' + image_name
    print(cmd_str)
    ret = os.system(cmd_str)
    print(ret)
    return ret

# print(getNodeInfo())


# print(getNodeAllContainer())
# print(getNodeInfo())
# print(getNodeImages())
# [{'SharedSize': -1, 'Created': 1526614418, 'RepoTags': ['ubuntu_image2/test:latest'], 'Id': 'sha256:0de9219d4d895bdfc19462dd623dd89581d5c5b35dc4a861c1c5cc7dfa14a38c', 'Labels': {}, 'Containers': -1, 'VirtualSize': 210625375, 'RepoDigests': None, 'Size': 210625375, 'ParentId': 'sha256:aa31cbb0f3c6743d22e15af9e1058d9e1becc10288593379f90231fec214a35d'}, {'SharedSize': -1, 'Created': 1524301503, 'RepoTags': ['ubuntu:vim'], 'Id': 'sha256:aa31cbb0f3c6743d22e15af9e1058d9e1becc10288593379f90231fec214a35d', 'Labels': {}, 'Containers': -1, 'VirtualSize': 210625313, 'RepoDigests': None, 'Size': 210625313, 'ParentId': ''}]
